<template>
	<view class="container">
		<NavBar title="扫码加油"/>
		<scroll-view scroll-y class="list" >
			<view class="box">
				
			</view>
			<!-- 设备信息卡片 -->
			<view class="equipment-card" @click="navigateToFuelRecords">
			  <view class="card-content">
			    <view class="title-row">
			      <text class="equipment-title">{{name}}</text>
			      <text class="equipment-id">{{code}}</text>
			    </view>
			    
			    <view class="equipment-image">
			      <!-- 设备图片 -->
			      <!-- <image class="equipment-img" src="/static/sb_image1.png" mode="widthFix"></image> -->
			    </view>
			    
			    <view class="stats-row">
			      <view class="stat-item">
			          <image src="/static/sb_time.png" class="stat-icon-img" mode="widthFix"></image>
			        <view class="stat-text">总计次数：{{info.num}}次</view>
			      </view>
			    </view>
			    
			    <view class="stats-row">
			      <view class="stat-item">
			          <image src="/static/sb_sj.png" class="stat-icon-img" mode="widthFix"></image>
			        <view class="stat-text">累计油量：{{info.oil}} L        |      {{info.amt}} 元</view>
			      </view>
			    </view>
			  </view>
			</view>
			<!-- 加油表单 -->
			<view class="form-container">
			  <!-- 油品选择 -->
			  <view class="form-item">
			    <view class="form-label">
			      <text>油品</text>
			    </view>
			    <view class="option-row">
			      <view 
			        v-for="(item, index) in fuelOptions" 
			        :key="index"
			        class="option-item"
			        :class="{ 'option-selected': formData.oilType === item.id }"
			        @click="selectFuel(item)"
			      >
			        <text class="option-text" :class="{ 'text-selected': formData.oilType === item.id }">{{item.specs+item.name }}</text>
			      </view>
			    </view>
			  </view>
			  <view class="form-item">
			    <view class="form-label">
			      <text>可领用量</text>
			    </view>
			    <view class="form-input klyNum">
			  		<view class="input-content">
			  			{{klyNum}}
			  		</view>
					<view class="klyNum-unit">
						L
					</view>
			    </view>
			  	
			  </view>
			  <!-- 加油量 -->
			  <view class="form-item">
			    <view class="form-label">
			      <text>加油量</text>
			    </view>
			    <view class="form-input">
			      <input 
				    class="input-content"
			        type="number" 
			        placeholder="请输入" 
			        v-model="form.oilNum"
			        placeholder-class="placeholder-style"
					@input='getmoney'
					@blur="blur('oilNum')"
			      />
				  
			    </view>
				<view class="">
					L
				</view>
			  </view>
			  
			  <!-- 油品单价 -->
			  <view class="form-item">
			    <view class="form-label">
			      <text>油品单价</text>
			    </view>
			    <view class="form-input">
			      <input 
				    class="input-content"
			        type="number" 
			        placeholder="请输入" 
			        v-model="form.unitPrice"
			        placeholder-class="placeholder-style"
					@input='getmoney'
					@blur="blur('unitPrice')"
			      />
			    </view>
				<view class="">
					元
				</view>
			  </view>
			  
			  <!-- 加油金额 -->
			  <view class="form-item">
			    <view class="form-label">
			      <text>加油金额</text>
			    </view>
			    <view class="form-input">
			      <input 
				    class="input-content"
			        type="number" 
			        v-model="form.oilAmt"
			        placeholder-class="placeholder-style"
					disabled
			      />
				  
			    </view>
				<view class="">
					元
				</view>
			  </view>
			  <!-- 油款承担方 -->
			  <view class="form-item">
			    <view class="form-label">
			      <text>油款承担方</text>
			    </view>
			    <view class="form-input">
			      {{formData.oilContractName=='null'?'暂无':formData.oilContractName}}
			    </view>
			  </view>
			  
			  <!-- 加油地点 -->
			  <!-- <view class="form-item">
			    <view class="form-label">
			      <text>加油地点</text>
			    </view>
			    <view class="form-input">
			      <input 
			        type="text" 
			        placeholder="请输入" 
			        v-model="fuelLocation"
			        placeholder-class="placeholder-style"
			      />
			    </view>
			  </view> -->
			  
			  <!-- 付款方式 -->
			  <!-- <view class="form-item">
			    <view class="form-label">
			      <text>付款方式</text>
			    </view>
			    <view class="option-row">
			      <view 
			        v-for="(item, index) in paymentOptions" 
			        :key="index"
			        class="option-item"
			        :class="{ 'option-selected': selectedPayment === item.dictValue }"
			        @click="selectPayment(item)"
			      >
			        <text class="option-text" :class="{ 'text-selected': selectedPayment === item }">{{ item.dictLabel }}</text>
			      </view>
			    </view>
			  </view> -->
			  
			  <!-- 附件上传 -->
			  <!-- <view class="form-item">
			    <view class="form-label">
			      <text>附件</text>
			    </view>
			    <view class="form-input">
			      <text class="placeholder-style">请上传加油票据</text>
			    </view>
			  </view> -->
			</view>
			
			<!-- 上传区域 -->
			<!-- <uv-upload
				:fileList="fileList1"
				name="1"
				multiple 
				:maxCount="4"
				@afterRead="afterRead" 
				@delete="deletePic" 
			></uv-upload> -->
			
			<!-- 提交按钮 -->
			<!-- <view class="submit-button-area">
			  <button class="submit-button" @click="submitForm">提交</button>
			</view> -->
			<uv-button class="submit-button" @click="submitForm" type="primary" shape="circle" text="提交"></uv-button>
		</scroll-view>
	</view>
</template>

<script>
	import NavBar from '@/components/NavBar/index.vue'
	import { upload,getStatistics,getSbmanageList,postRefuel,datatype,oilsInfo } from '@/utils/app.js'
	import { BASEURL } from '@/utils/request.js'
	export default {
		components:{NavBar},
		data() {
			return {
				fuelOptions: [],
				code:'',
				name:'',
				selectedFuel: '92#',
				fuelAmount: '',
				klyNum:'',
				fuelCost: '',
				unitPrice:'',
				fuelLocation: '',
				paymentOptions: ['支付宝', '微信', '现金', '其他'],
				selectedPayment: '支付宝',
				fileList1: [],
				headers: {},
				info:{},
				facilityId:'',
				form:{
					oilNum:'',
					unitPrice:'',
					oilAmt:''
				},
				formData:{
					oilType:'',
					oilContractName:'',
					projectId:'',
					drawContractId:'',
					cycleId:'',
					facilityId:''
				}
			}
		},
		onLoad(optiion) {
			console.log(optiion);
			this.formData.drawContractId=optiion.drawContractId
			this.formData.oilContractName = optiion.oilContractName
			this.formData.projectId = optiion.projectId
			this.formData.cycleId = optiion.cycleId
			this.formData.facilityId = optiion.facilityId
			this.name=optiion.name
			this.code=optiion.code
			this.oilsInfoList({name:'柴油',unitTwo:'L',unit:'升',projectId:optiion.projectId})
			// {dictType:'oil_type'}
			// this.datatypeList('oil_type')
			// this.datatypeList('refuel_pay')
			// getSbmanageList().then(res=>{
			// 	console.log(res);
			// })
			this.getStatisticsList({facilityId:optiion.facilityId,projectId:optiion.projectId})
			const token = uni.getStorageSync("token");
			console.log('token',token);
			this.headers = {
				
				Authorization: "Bearer " + token,
			  }
		},
		methods: {
			blur(e){
				if(this.form[e] < 0){
					this.form[e] = ''
					uni.showToast({
					    title: '只能输入大于0的数字',
					    icon: 'none'
					});
				}
			},
			getmoney(){
				if(this.form.oilNum && this.form.unitPrice){
					this.form.oilAmt = this.form.oilNum * this.form.unitPrice
				}
			},
			datatypeList(data){
				console.log(222222);
				datatype(data).then(res=>{
					if(data=='oil_type'){
						this.fuelOptions =  res.data
						this.selectedFuel=res.data[0].dictValue
						
					}else{
						this.paymentOptions = res.data
						this.selectedPayment = res.data[0].dictValue
					}
					
				})
			},
			// 加油统计
			getStatisticsList(data){
				getStatistics(data).then(res=>{
					if(res.code==200){
						this.info=res.data
					}
				})
			},
			// 油品类别
			oilsInfoList(data){
				oilsInfo(data).then(res=>{
					console.log(res.data);
					this.fuelOptions = res.data
					this.formData.oilType=res.data[0]?res.data[0].id:''
					this.klyNum=res.data[0]?res.data[0].klyNum:''
					
				})
			},
			selectFuel(fuel) {
			  this.formData.oilType = fuel.id;
			  this.klyNum = fuel.klyNum
			},
			selectPayment(payment) {
			  this.selectedPayment = payment.dictValue;
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				console.log('1111',event);
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i])
					console.log(result);
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			async uploadFilePromise(url) {
				const token = uni.getStorageSync("token");
				// await this.blobUrlToFile(url.url, url.name)BASEURL
				const file = await this.blobUrlToFile(url.url, url.name);
				console.log(2222,file);
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${BASEURL}/common/upload`,// 仅为示例，非真实的接口地址
						// url: 'http://192.168.0.5:8091/common/upload',// 仅为示例，非真实的接口地址
						header: {
                         'Authorization': token,
						 // 'content-type' : 'multipart/form-data'
                        },
						filePath: url.url,
						// files:[file],
						// file:file,
						name: 'file',
						formData: {
							// type: url.name,
							
						},
						success: (res) => {
							console.log(res);
							
							resolve(JSON.parse(res.data).annexUrl)
						},
						
					});
				})
				// const formData = new FormData();
				// formData.append('file', file);
				// console.log(formData);	
				
			},
			async blobUrlToFile(blobUrl, fileName) {
			    try {
					return new Promise((resolve, reject)=>{
						uni.request({
						    url: blobUrl,
						    method: 'GET',
						    responseType: 'arraybuffer',
							success: function(res) {
									console.log(res);
									const blob = new Blob([res.data], { type: res.header['Content-Type'] });
									console.log(blob);
									 
									return resolve(new File([blob], fileName, {
									    type: blob.type,
									    lastModified: Date.now()
									}))
								}
						});
					})
					
			    } catch (error) {
			        console.error('转换失败:', error);
			        throw error;
			    }
			},
			submitForm(){
				
				// 表单验证
				if (!this.form.oilNum) {
				  uni.showToast({
				    title: '请输入加油量',
				    icon: 'none'
				  });
				  return;
				}
				if (Number(this.form.oilNum)>Number(this.klyNum)) {
				  uni.showToast({
				    title: '加油量不能大于可领用量',
				    icon: 'none'
				  });
				  return;
				}
				if (!this.form.unitPrice) {
				  uni.showToast({
				    title: '请输入油品单价',
				    icon: 'none'
				  });
				  return;
				}
				if (!this.form.oilAmt) {
				  uni.showToast({
				    title: '请输入加油金额',
				    icon: 'none'
				  });
				  return;
				}
				
				
					
				// console.log(data);
				postRefuel({...this.form,...this.formData}).then(res=>{
					this.form={}
					console.log(res);
					uni.switchTab({
					  url: '/pages/facility/index'
					});
					
				})
				
			},
			navigateToFuelRecords() {
			  uni.navigateTo({
			    url: '/pages/equipment/refuel/records?facilityId='+this.formData.facilityId
			  });
			},
			
		}
	}
</script>

<style lang="scss" scoped>
*{
	box-sizing: border-box;
}
.list{
	height: calc(100vh - 180rpx);
	background-color: #f6f7f9;
	
	.box{
		width: 100%;
		height: 20rpx;
	}
	.equipment-card{
		margin: 20rpx auto;
		margin-top: 0;
		width: 700rpx;
		// height: 450rpx;
		border-radius: 16px;
		background-color: #fff;
		
		.card-content{
			
			padding: 24rpx 16rpx 24rpx 48rpx;
		}
		.equipment-image{
			width: 310rpx;
			margin: 30rpx auto;
			.equipment-img{
				width: 310rpx;
				
			}
		}
		.title-row{
			height: 48rpx;
			line-height: 48rpx;
			.equipment-title{
				margin-right: 24rpx;
				font-family: DM Sans;
				font-size: 30rpx;
				font-weight: bold;
				color: #242731;
				
			}
			.equipment-id{
				font-size: 30rpx;
				font-weight: normal;
				color: #72767C;
			}
		}
		.stats-row{
			
			.stat-item{
				display: flex;
				align-items: center;
				height: 48rpx;
				line-height: 48rpx;
			}
			.stat-icon-img{
				width: 32rpx;
				margin-right: 16rpx;
				font-size: 30rpx;
			}
			.stat-text{
				height: 48rpx;
				line-height: 48rpx;
				font-size: 30rpx;
				color: #72767C;
				
			}
		}
	}
	.form-container{
		background-color: #fff;
		
		.form-item{
			display: flex;
			align-items: center;
			height: 112rpx;
			padding: 0 30rpx;
			font-size: 30rpx;
			border-bottom: 1rpx solid #E6EAF3;
			.form-input{
				font-size: 30rpx;
			}
			.input-content{
				width: 400rpx;
			}
			.form-label{
				width: 162rpx;
				margin-right: 20rpx;
				font-size: 30rpx;
			}
			.klyNum{
				flex: 1;
				display: flex;
				justify-content: space-between;
				.klyNum-unit{
					// width: 120rpx;
					flex: 1;
				}
			}
			.option-row{
				flex: 1;
				height: 72rpx;
				display: flex;
				.option-item{
					flex: 1;
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: 28rpx;
					color: #4E5969;
				}
				.option-selected{
					color: #165DFF;
					background-color: #E8F3FF;
					border-radius: 10rpx;
				}
			}
			
		}
	}
	.submit-button{
		width: 630rpx;
		margin: 50rpx auto 0;
	}
}
</style>
